<template>
<div id="bd">
    <div v-if="blogNotExist" class="notExist">
        抱歉，该文章不存在呢
        <img width="31px" style="position: relative;top: 6px" src="https://res.wx.qq.com/mpres/htmledition/images/icon/emotion/50.gif">
    </div>
    <template v-else>
        <el-backtop></el-backtop>   <!--回到顶部按钮-->
        <div class="blog" v-loading="loading_blog">
            <div class="head" style="zoom: 1">
                <el-avatar :size="45" :src="blog.userAvatar+'?n='+$store.state.timestamp"></el-avatar>
                <div>
                    <div class="nickname">{{blog.userNickname}}</div>
                    <div class="created">{{blog.created}}</div>
                </div>
            </div>
            <div style="padding: 5px">
                <h3 style="font-size: 35px">{{blog.title}}</h3>
                <el-divider></el-divider>
                <div class="markdown-body" v-html="blog.content"></div>
            </div>
        </div>

        <div class="comments" v-loading="loading_blog" id="comments">
            <!--发表评论模块-->
            <div style="font-size: 20px;padding: 10px 15px">
                <div>评论&nbsp;{{blog.comment}}</div>
                <div style="display: flex;margin: 10px 0px">
                    <el-input
                            class="input"
                            id="input"
                            type="textarea"
                            :autosize="{ minRows: 2, maxRows: 4}"
                            placeholder="发表评论"
                            v-model="comment"
                            size="medium">
                    </el-input>
                    <div style="display: flex;flex-direction:column">
                        <button class="send-button" @click="sendComment"><i class="el-icon-edit">发送</i></button>
                        <div style="margin: 5px 0 0 10px;">
                            <span @click="$refs.emotion.reverseShow()">
                                <img src="../../public/emoji.png" width="23" style="opacity: 0.6;cursor: pointer">
                            </span>
                            <!--表情组件-->
                            <Emotion ref="emotion" @clickEmo="clickEmotion" class="emotion"></Emotion>
                        </div>
                    </div>
                </div>
                <div class="comments-line"></div>
            </div>
            <!--显示评论模块-->
            <div v-for="(comment,key) in comments" :key="key" class="comment" v-loading="loading_comment">
                <div class="head">
                    <el-avatar :size="45" :src="comment.userAvatar+'?n='+$store.state.timestamp"></el-avatar>
                    <div>
                        <div class="nickname">{{comment.userNickname}}</div>
                        <div class="created">
                            {{comment.created}}
                            <span class="reply" @click="clickReply(comment.userNickname)">回复</span>
                        </div>
                    </div>
                </div>
                <!--删除按钮，要检验删除权限-->
                <div v-if="verifyDeleteAuth(comment.userId)" class="comment-delete">
                    <el-dropdown trigger="click">
                        <span class="el-dropdown-link">
                           <i class="el-icon-more-outline"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item icon="el-icon-delete"  @click.native="deleteCommentById(comment.id)">删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>
                <div class="comment-content" v-html="comment.content"></div>
                <div v-if="key!=comments.length-1" class="comment-line"></div>
            </div>
            <!--分页组件-->
            <div style="padding-top: 10px" v-if="blog.comment>20">
                <el-pagination style="text-align: center"
                               background
                               layout="prev, pager, next"
                               :total="total"
                               :page-size="pageSize"
                               @current-change="handleCurrentChange(blog.id)"
                               :current-page.sync="currentPage">
                </el-pagination>
            </div>
        </div>
    </template>
</div>
</template>

<script>
    import 'github-markdown-css'    //markdown解析后的文本，引入这个css，在标签中使用，让文本显示的更规范
    import {marked} from 'marked'   //用于解析.md文本
    import highlight from "highlight.js";   //用于代码块高亮显示
    import "highlight.js/styles/github.css";         // 清新风格
    //import 'highlight.js/styles/atom-one-dark.css' // 黑色风格

    import Emotion from "@/components/Emotion";
    export default {
        name: "BlogDetail",
        components:{Emotion},
        data(){
            return{
                blog:{
                    userAvatar: this.$config.baseURL+'/user/getAvatar/default_avatar.png',
                    userId: 0
                },   //初始化一个默认头像，否则axios异步请求没结束渲染头像时，该参数未定义报错
                comments:[],
                currentPage:1,   //页码
                total:0,       //评论总数
                pageSize:20,    //每页条数
                comment:'',     //发表的评论的内容
                loading_blog: true,     //博客正在加载标志
                loading_comment: true,   //评论正在加载标志
                blogNotExist: false         //文章不存在标志
            }
        },
        methods: {
            handleCurrentChange(blogId){
                //滚动到评论顶端
                if(document.getElementById("comments")!=null){
                    const toComments = document.getElementById("comments");
                    const topPosition = toComments.getBoundingClientRect().top + window.pageYOffset-70; // 获取目标元素当前位置
                    window.scrollTo({
                        top: topPosition,
                        behavior: 'smooth' // 平滑滚动
                    });
                }

                this.getComments(blogId);
            },
            getComments(blogId){
                this.$router.replace({query:{page:this.currentPage}})
                this.loading_comment = true;
                this.$axios.get('/comment/get/'+blogId+'?currentPage='+this.currentPage).then(res=>{
                    this.comments = res.data.data.records;
                    this.currentPage = res.data.data.current;
                    this.total = res.data.data.total;
                    this.pageSize = res.data.data.size;
                    this.loading_comment = false;
                })
            },
            verifyDeleteAuth(commentUserId){
                if(this.$store.state.userInfo){
                    let loginUserId = this.$store.state.userInfo.id
                    return loginUserId===commentUserId || loginUserId===this.blog.userId || loginUserId===1
                }
                return false
            },
            deleteCommentById(commentId){
                this.$axios.post('/comment/delete/'+commentId).then(res=>{
                    if(res.data.code === 200){
                        this.getComments(this.blog.id)
                        this.$message.success('删除成功')
                        this.blog.comment = this.blog.comment-1
                    }
                })
            },
            clickReply(userNickname){
                this.comment = '@'+userNickname+'：'
                document.getElementById('input').scrollIntoViewIfNeeded()

            },
            sendComment(){
                if(this.$store.state.userInfo){
                    const commentObj = {
                        blogId: this.blog.id,
                        userId: this.$store.state.userInfo.id,
                        content: this.comment.replace(new RegExp("\\[\\[.*?\\]\\]",'g'),str=>{
                            let emoArr = str.match(new RegExp("(?<=\\[\\[).*?(?=\\]\\])",'g'))
                            let index = this.$refs.emotion.getIndexOfEmotion(emoArr[0])
                            return '<img style="height:26px" src="https://res.wx.qq.com/mpres/htmledition/images/icon/emotion/'+index+'.gif">'
                        })   //用正则表达式将表情的中文文字替换成html标签
                    }
                    this.$axios.post('/comment/add', commentObj).then(res => {
                        if(res.data.code == 200){
                            this.currentPage = 1
                            this.getComments(this.blog.id)
                            this.blog.comment = this.blog.comment+1
                            this.comment=''
                        }
                    })
                }else {
                    this.$store.commit('set_needLogin',{flag: true, msg:'登陆后才能发表评论'})
                }
            },
            clickEmotion(emoName){
                this.comment += emoName
            }
        },
        created() {
            const blogId = this.$route.params.blogId;
            this.$axios.get('/blog/get/'+blogId).then(res=>{
                if(!res.data.data){
                    this.blogNotExist = true
                    this.loading_blog = false
                    return
                }
                this.blog = res.data.data;

                //markdown文本解析
                marked.setOptions({     //添加高亮选项再解析
                    highlight: (code,lang)=>{
                        let language = highlight.getLanguage(lang) ? lang : 'plaintext';
                        return highlight.highlight(code,{language}).value;
                    }
                })
                this.blog.content = marked.parse(this.blog.content)

                this.loading_blog = false
            })

            if(this.$route.query.page){
                this.currentPage = parseInt(this.$route.query.page)
            }
            this.getComments(blogId)
        }
    }
</script>

<style scoped>
    #bd{
        margin: 0 auto 20px auto;
        max-width: 960px;
    }
    .notExist{
        font-size: 25px;
        text-align: center;
        background-color: white;
        height: 100px;
        line-height: 100px;
    }
    .blog{
        /*box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .12);*//*盒子阴影*/
        padding: 40px 35px;
        background-color: white;
    }
    .head{
        align-items: center;  /*上下居中*/
        display: flex;
        margin-bottom: 10px;
    }
    .el-avatar{
        margin-right: 5px;
    }
    .nickname{
         font-size: 14px;
         color: #47292e;
     }
    .created{
        margin-top: 3px;
        font-size: small;
        color: rgba(0, 0, 0, 0.5);
    }
    .reply{
        cursor: pointer;
        margin-left: 10px;
    }
    .reply:hover{
        color: #31c2fc;
    }
    .comments{
        margin-top: 20px;
        /*box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .12);*//*盒子阴影*/
        padding: 10px 20px 30px 20px;
        background-color: white;
    }
    .emotion{
        position: absolute;
    }
    .comments-line{
        border-top: 2px solid #EBEEF5;
        margin: 10px 32px 10px 0;
    }
    .comment{
        padding-top: 10px;
        padding-left: 15px;
    }
    .comment-content{
        font-size: 20px;
        padding: 5px 48px;
        display: flex;
    }
    .comment-delete{
        float: right;
        position: relative;
        bottom: 45px;
        padding-right: 51px;
    }
    .comment-line{
        border-top: 2px solid #EBEEF5;
        margin: 10px 48px;
    }
    .el-dropdown-link {
        cursor: pointer;
        color: #409EFF;
    }
    .input{
        max-width: 500px;
        min-height: 44px;
        font-size: 18px;
    }
    .send-button{
        max-height: 40px;
        background-color: orange;
        display: inline-block;
        line-height: 1;
        cursor: pointer;
        border: 1px solid orange;
        color: white;
        padding: 12px 20px;
        font-size: 14px;
        border-radius: 4px;
        margin-left: 10px;
    }
    @media (max-width: 600px) { /*媒体宽度低于600px时*/
        #bd{
            margin: 0;
        }
        .blog{
            padding: 40px 5px;
        }
        .comments{
            padding: 10px 5px 30px 5px;
        }
        .emotion{
            right: 80px;
        }
        .comments-line{
            margin: 10px 14px 10px 0;
        }
        .comment{
            padding-top: 10px;
            padding-left: 5px;
        }
        .send-button{
            padding: 10px 5px;
        }
        .input{
            max-width: 250px;
            font-size: 15px;
        }
        .head{
            zoom: 0.8;
        }
        .comment-content{
            padding-right: 5px;
            zoom: 0.8;
        }
        .comment-line{
            margin: 10px 30px 10px 39px;
        }
        .comment-delete{
            padding-right: 33px;
        }
    }
</style>
